package com.hugedata.cdnserver.util;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Properties;

public final class ECMPath
{
    private ECMPath()
    {

    }

    public static String getECMRoot()
    {
        return getClassLocationBefore(ECMPath.class, "WEB-INF");
    }

    private static String getClassLocationBefore(final Class<ECMPath> cls,
            final String folder)
    {
        String returnStr = getClassLocation(cls);
        int iPos = returnStr.indexOf(folder);
        if (iPos >= 0)
        {
            returnStr = returnStr.substring(0, iPos);
        }
        if (!returnStr.endsWith("/"))
        {
            returnStr += "/";
        }

        Properties props = System.getProperties();
        String osName = props.getProperty("os.name");

        if (-1 == osName.toLowerCase().indexOf("windows"))
        {
            returnStr = "/" + returnStr;
        }
        return returnStr;
    }

    private static String getClassLocation(final Class<ECMPath> cls)
    {
        String returnStr = "";
        if (cls != null)
        {
            URL url = cls.getProtectionDomain().getCodeSource().getLocation();
            try
            {
                returnStr = URLDecoder.decode(url.getPath(), "utf-8");
            }
            catch (UnsupportedEncodingException e)
            {
                e.printStackTrace();
            }
            if (returnStr.length() != 0)
            {
                returnStr = returnStr.substring(1);
            }
        }
        return returnStr;
    }

    public static String getPathofConigProperties(String filePath)
    {
        return ECMPath.getECMRoot() + "WEB-INF/classes/" + filePath;
    }

    public static String getMessageResourcesPath()
    {
        return ECMPath.getECMRoot()
                + "WEB-INF/classes/MessageResources.properties";
    }
}
